<template>
  <view class="service-page">
    <!-- 导航栏 -->
    <up-navbar :placeholder="true" left-icon="arrow-left" title="在线客服" bg-color="#f8f8f8" 
               title-color="#333" @left-click="goBack"></up-navbar>
    
    <!-- 客服状态栏 -->
    <view class="service-status">
      <view class="status-info">
        <view class="avatar-wrapper">
          <up-avatar :src="serviceInfo.avatar" size="40"></up-avatar>
          <view class="online-dot" :class="{ online: serviceInfo.isOnline }"></view>
        </view>
        <view class="service-details">
          <text class="service-name">{{ serviceInfo.name }}</text>
          <text class="service-status-text">{{ serviceInfo.isOnline ? '在线' : '离线' }}</text>
        </view>
      </view>
      <view class="response-time">
        <text>平均响应时间：{{ serviceInfo.responseTime }}</text>
      </view>
    </view>
    
    <!-- 聊天容器 -->
    <scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" scroll-with-animation>
      <view class="chat-list">
        <!-- 欢迎消息 -->
        <view v-if="messageList.length === 0" class="welcome-message">
          <view class="welcome-card">
            <up-icon name="customer-service" size="60" color="#4CAF50"></up-icon>
            <text class="welcome-title">欢迎咨询在线客服</text>
            <text class="welcome-desc">我们的客服团队将为您提供专业的服务和支持</text>
          </view>
          
          <!-- 常见问题 -->
          <view class="common-questions">
            <text class="common-title">常见问题</text>
            <view class="question-list">
              <view v-for="(item, index) in commonQuestions" :key="index" 
                    class="question-item" @click="sendCommonQuestion(item)">
                <up-icon name="help" size="16" color="#666"></up-icon>
                <text>{{ item }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 消息列表 -->
        <view v-for="(message, index) in messageList" :key="index" class="message-item">
          <!-- 用户消息 -->
          <view v-if="message.type === 'user'" class="user-message">
            <view class="message-content user-content">
              <text>{{ message.content }}</text>
              <view class="message-time">{{ formatTime(message.time) }}</view>
            </view>
            <up-avatar :src="userInfo.avatar" size="36"></up-avatar>
          </view>
          
          <!-- 客服回复 -->
          <view v-else class="service-message">
            <up-avatar :src="serviceInfo.avatar" size="36"></up-avatar>
            <view class="message-content service-content">
              <view class="service-header">
                <text class="service-name-small">{{ serviceInfo.name }}</text>
                <text class="message-time">{{ formatTime(message.time) }}</text>
              </view>
              <view v-if="message.loading" class="loading-dots">
                <view class="dot"></view>
                <view class="dot"></view>
                <view class="dot"></view>
              </view>
              <text v-else class="message-text">{{ message.content }}</text>
            </view>
          </view>
        </view>
        
        <!-- 正在输入提示 -->
        <view v-if="isServiceTyping" class="typing-indicator">
          <up-avatar :src="serviceInfo.avatar" size="24"></up-avatar>
          <text class="typing-text">客服正在输入...</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area">
      <!-- 快捷回复 -->
      <view v-if="showQuickReplies" class="quick-replies">
        <view v-for="(reply, index) in quickReplies" :key="index" 
              class="quick-reply-item" @click="sendQuickReply(reply)">
          {{ reply }}
        </view>
      </view>
      
      <view class="input-container">
        <view class="input-wrapper">
          <up-input v-model="inputText" 
                    placeholder="请输入您的问题..." 
                    :border="'none'"
                    :clearable="true"
                    @keyboardheightchange="handleKeyboard"
                    @focus="handleInputFocus"
                    @blur="handleInputBlur"
                    class="message-input">
          </up-input>
        </view>
        
        <view class="action-buttons">
          <view class="emoji-btn" @click="toggleQuickReplies">
            <up-icon name="smile" size="24" color="#666"></up-icon>
          </view>
          <view class="send-btn" @click="sendMessage" :class="{ active: canSend }">
            <up-icon v-if="!isLoading" name="arrow-right" size="20" color="#fff"></up-icon>
            <up-loading-icon v-else color="#fff" size="16"></up-loading-icon>
          </view>
        </view>
      </view>
      
      <!-- 功能按钮 -->
      <view class="function-buttons">
        <view class="function-btn" @click="makePhoneCall">
          <up-icon name="phone" size="18" color="#666"></up-icon>
          <text>电话客服</text>
        </view>
        
        <view class="function-btn" @click="showServiceHours">
          <up-icon name="clock" size="18" color="#666"></up-icon>
          <text>服务时间</text>
        </view>
        
        <view class="function-btn" @click="transferToHuman">
          <up-icon name="account" size="18" color="#666"></up-icon>
          <text>转人工</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted } from 'vue'

// 响应式数据
const inputText = ref('')
const messageList = reactive([])
const scrollTop = ref(0)
const isLoading = ref(false)
const keyboardHeight = ref(0)
const showQuickReplies = ref(false)
const isServiceTyping = ref(false)

// 用户信息
const userInfo = reactive({
  avatar: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',
  name: '用户'
})

// 客服信息
const serviceInfo = reactive({
  avatar: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',
  name: '小雅客服',
  isOnline: true,
  responseTime: '2分钟'
})

// 常见问题
const commonQuestions = reactive([
  '如何注册会员？',
  '忘记密码怎么办？',
  '作品如何收藏？',
  '如何联系客服？',
  '展览门票价格？'
])

// 快捷回复
const quickReplies = reactive([
  '好的，谢谢',
  '我知道了',
  '还有其他问题',
  '非常满意',
  '需要进一步了解'
])

// 客服回复模板
const serviceResponses = {
  '如何注册会员？': '您好！注册会员很简单：\n1. 点击首页右上角"登录"按钮\n2. 选择"立即注册"\n3. 填写手机号并获取验证码\n4. 设置密码完成注册\n\n注册成功后即可享受会员专属服务！',
  
  '忘记密码怎么办？': '别担心，找回密码很容易：\n1. 在登录页面点击"忘记密码"\n2. 输入注册时的手机号\n3. 获取短信验证码\n4. 设置新密码\n\n如仍有问题，请联系客服热线：400-123-4567',
  
  '作品如何收藏？': '收藏作品的方法：\n1. 进入作品详情页\n2. 点击右下角"收藏"图标\n3. 登录后即可成功收藏\n\n您可以在"我的-收藏"中查看所有收藏的作品。',
  
  '如何联系客服？': '联系客服的方式：\n1. 在线客服：工作日9:00-18:00\n2. 客服热线：400-123-4567\n3. 邮箱：service@gallery.com\n4. 微信公众号：书法艺术馆\n\n我们将竭诚为您服务！',
  
  '展览门票价格？': '展览门票信息：\n• 成人票：68元/人\n• 学生票：38元/人（凭学生证）\n• 儿童票：免费（1.2米以下）\n• VIP票：168元/人（含导览服务）\n\n在线购票享受95折优惠！'
}

// 计算属性
const canSend = computed(() => {
  return inputText.value.trim().length > 0 && !isLoading.value
})

// 方法
const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack({
      fail: () => {
        uni.switchTab({ url: '/pages/index/index' })
      }
    })
  } else {
    uni.switchTab({ url: '/pages/index/index' })
  }
}

const sendCommonQuestion = (question) => {
  inputText.value = question
  sendMessage()
}

const sendQuickReply = (reply) => {
  inputText.value = reply
  sendMessage()
  showQuickReplies.value = false
}

const sendMessage = async () => {
  if (!canSend.value) return
  
  const message = inputText.value.trim()
  inputText.value = ''
  showQuickReplies.value = false
  
  // 添加用户消息
  messageList.push({
    type: 'user',
    content: message,
    time: new Date()
  })
  
  // 显示正在输入
  isServiceTyping.value = true
  scrollToBottom()
  
  // 模拟客服响应延迟
  setTimeout(() => {
    isServiceTyping.value = false
    
    // 添加客服回复
    messageList.push({
      type: 'service',
      content: '',
      loading: true,
      time: new Date()
    })
    
    isLoading.value = true
    scrollToBottom()
    
    // 模拟打字效果
    setTimeout(() => {
      const lastMessage = messageList[messageList.length - 1]
      lastMessage.loading = false
      lastMessage.content = getServiceResponse(message)
      isLoading.value = false
      scrollToBottom()
    }, 1000 + Math.random() * 1000)
  }, 800)
}

const getServiceResponse = (userMessage) => {
  // 检查预设回复
  for (const [key, value] of Object.entries(serviceResponses)) {
    if (userMessage.includes(key) || key.includes(userMessage)) {
      return value
    }
  }
  
  // 关键词匹配
  if (userMessage.includes('价格') || userMessage.includes('费用') || userMessage.includes('多少钱')) {
    return '关于价格问题，我们有多种套餐可选：\n• 基础服务：免费\n• 高级服务：68元/月\n• VIP服务：168元/月\n\n具体价格可能因服务内容而异，建议您详细咨询。'
  }
  
  if (userMessage.includes('时间') || userMessage.includes('营业') || userMessage.includes('开放')) {
    return '我们的服务时间：\n• 在线客服：9:00-18:00（工作日）\n• 展馆开放：9:00-17:00（每日）\n• 客服热线：9:00-21:00（每日）\n\n节假日可能有调整，请关注官方通知。'
  }
  
  // 默认回复
  return '感谢您的咨询！我已收到您的问题，正在为您查询相关信息。如需要更详细的帮助，建议您转接人工客服，我们的专业客服会为您提供更准确的解答。'
}

const formatTime = (time) => {
  return new Date(time).toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery()
    query.select('.chat-list').boundingClientRect(data => {
      if (data) {
        scrollTop.value = data.height
      }
    }).exec()
  })
}

const handleKeyboard = (e) => {
  keyboardHeight.value = e.height
  // 键盘弹起时自动滚动到底部
  setTimeout(() => {
    scrollToBottom()
  }, 100)
}

const handleInputFocus = () => {
  showQuickReplies.value = false
}

const handleInputBlur = () => {
  // 延迟隐藏快捷回复，以便点击生效
  setTimeout(() => {
    // showQuickReplies.value = false
  }, 200)
}

const toggleQuickReplies = () => {
  showQuickReplies.value = !showQuickReplies.value
}

const makePhoneCall = () => {
  const phoneNumber = '400-123-4567'
  
  uni.showModal({
    title: '联系客服',
    content: `是否拨打客服热线：${phoneNumber}？`,
    confirmText: '拨打',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        uni.makePhoneCall({
          phoneNumber,
          success: () => {
            console.log('拨打电话成功')
          },
          fail: (error) => {
            console.error('拨打电话失败:', error)
            uni.showToast({ 
              title: '拨打失败，请手动拨打', 
              icon: 'none',
              duration: 3000
            })
          }
        })
      }
    }
  })
}

const showServiceHours = () => {
  uni.showModal({
    title: '客服服务时间',
    content: '在线客服：9:00-18:00（工作日）\n客服热线：9:00-21:00（每日）\n\n如有紧急问题，请拨打热线电话',
    showCancel: false
  })
}

const transferToHuman = () => {
  uni.showModal({
    title: '转接人工客服',
    content: '当前在线客服较忙，预计等待时间3-5分钟，是否继续等待？',
    confirmText: '继续等待',
    cancelText: '稍后再试',
    success: (res) => {
      if (res.confirm) {
        // 模拟转接过程
        messageList.push({
          type: 'service',
          content: '正在为您转接人工客服，请稍等...',
          time: new Date()
        })
        scrollToBottom()
        
        setTimeout(() => {
          serviceInfo.name = '人工客服小王'
          messageList.push({
            type: 'service',
            content: '您好！我是人工客服小王，很高兴为您服务。请问有什么可以帮助您的？',
            time: new Date()
          })
          scrollToBottom()
        }, 3000)
      }
    }
  })
}

onMounted(async () => {
  // 页面加载完成后的初始化
  scrollToBottom()
})
</script>

<style lang="scss" scoped>
.service-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f6fa;
}

.service-status {
  background: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
  
  .status-info {
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;
    
    .avatar-wrapper {
      position: relative;
      margin-right: 20rpx;
      
      .online-dot {
        position: absolute;
        bottom: 2rpx;
        right: 2rpx;
        width: 20rpx;
        height: 20rpx;
        border-radius: 50%;
        background: #ccc;
        border: 3rpx solid #fff;
        
        &.online {
          background: #4CAF50;
        }
      }
    }
    
    .service-details {
      .service-name {
        display: block;
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 4rpx;
      }
      
      .service-status-text {
        font-size: 24rpx;
        color: #4CAF50;
      }
    }
  }
  
  .response-time {
    text {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.chat-container {
  flex: 1;
  padding: 20rpx 30rpx;
  overflow-y: auto;
}

.chat-list {
  min-height: 100%;
  padding-bottom: 20rpx;
}

.welcome-message {
  .welcome-card {
    background: #fff;
    border-radius: 20rpx;
    padding: 60rpx 40rpx;
    text-align: center;
    margin-bottom: 40rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    
    .welcome-title {
      display: block;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin: 30rpx 0 20rpx;
    }
    
    .welcome-desc {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
  
  .common-questions {
    .common-title {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .question-list {
      display: flex;
      flex-direction: column;
      gap: 16rpx;
      
      .question-item {
        display: flex;
        align-items: center;
        gap: 16rpx;
        background: #fff;
        border-radius: 16rpx;
        padding: 24rpx 30rpx;
        font-size: 28rpx;
        color: #333;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
        transition: all 0.3s;
        
        &:active {
          transform: scale(0.98);
          background: #f8f9fa;
        }
      }
    }
  }
}

.message-item {
  margin-bottom: 30rpx;
  
  .user-message {
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    gap: 16rpx;
    
    .user-content {
      background: linear-gradient(135deg, #4CAF50, #45A049);
      color: #fff;
      max-width: 520rpx;
      
      .message-time {
        font-size: 20rpx;
        opacity: 0.8;
        margin-top: 8rpx;
        text-align: right;
      }
    }
  }
  
  .service-message {
    display: flex;
    align-items: flex-start;
    gap: 16rpx;
    
    .service-content {
      background: #fff;
      color: #333;
      max-width: 520rpx;
      
      .service-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8rpx;
        
        .service-name-small {
          font-size: 24rpx;
          color: #4CAF50;
          font-weight: 500;
        }
        
        .message-time {
          font-size: 20rpx;
          color: #999;
        }
      }
      
      .loading-dots {
        display: flex;
        gap: 8rpx;
        padding: 10rpx 0;
        
        .dot {
          width: 12rpx;
          height: 12rpx;
          background: #ccc;
          border-radius: 50%;
          animation: loading 1.4s infinite ease-in-out;
          
          &:nth-child(1) { animation-delay: -0.32s; }
          &:nth-child(2) { animation-delay: -0.16s; }
        }
      }
      
      .message-text {
        line-height: 1.5;
        white-space: pre-line;
      }
    }
  }
  
  .message-content {
    padding: 24rpx 30rpx;
    border-radius: 20rpx;
    font-size: 28rpx;
    word-wrap: break-word;
  }
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 20rpx;
  
  .typing-text {
    font-size: 24rpx;
    color: #666;
    font-style: italic;
  }
}

.input-area {
  background: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  /* 键盘适配 */
  padding-bottom: calc(20rpx + env(keyboard-inset-height, 0rpx));
  transition: padding-bottom 0.3s ease;
  
  .quick-replies {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 20rpx;
    
    .quick-reply-item {
      background: #f0f8ff;
      color: #4CAF50;
      padding: 12rpx 20rpx;
      border-radius: 30rpx;
      font-size: 24rpx;
      border: 1rpx solid #4CAF50;
      transition: all 0.3s;
      
      &:active {
        background: #4CAF50;
        color: #fff;
      }
    }
  }
  
  .input-container {
    display: flex;
    align-items: center;
    background: #f5f6fa;
    border-radius: 50rpx;
    padding: 12rpx 20rpx;
    margin-bottom: 20rpx;
    
    .input-wrapper {
      flex: 1;
      margin-right: 16rpx;
    }
    
    .message-input {
      font-size: 28rpx;
    }
    
    .action-buttons {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .emoji-btn {
        padding: 8rpx;
        border-radius: 50%;
        transition: all 0.3s;
        
        &:active {
          background: #e0e0e0;
        }
      }
      
      .send-btn {
        width: 64rpx;
        height: 64rpx;
        background: #ccc;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s;
        
        &.active {
          background: #4CAF50;
          transform: scale(1.05);
        }
      }
    }
  }
  
  .function-buttons {
    display: flex;
    justify-content: space-around;
    
    .function-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8rpx;
      padding: 16rpx 20rpx;
      border-radius: 12rpx;
      transition: all 0.3s;
      
      text {
        font-size: 24rpx;
        color: #666;
      }
      
      &:active {
        background: #f5f6fa;
      }
    }
  }
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>